import axios from 'axios'
// 实例化
const instance = axios.create({
    baseURL: '',
    timeout: 5000,
})
// 添加请求拦截
instance.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem('token')
        config.headers.Authorization = 'Bearer ' + token
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 添加响应拦截
instance.interceptors.response.use(
    (config) => {
        return config
    },
    (error) => {
        if (error.message.includes('timeout')) {
            alert('页面超时处理')
        }
        const code = error.response.status
        switch (code) {
            case 400:
                console.log('请求错误')
                break;
            case 401:
                //、token过期处理，清除缓存，返回登录页
                localStorage.removeItem('token')
                // window.location.href = '/login'
                console.log('未授权')
                break;
            case 403:
                console.log('禁止访问')
                break;
            case 404:
                console.log('资源未找到')
                break;
            case 500:
                console.log('服务器内部错误')
                break;
        }

        return Promise.reject(error)
    }
)

// 抛出
export default instance